package zy.service.buy.order.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.base.depot.DepotDAO;
import zy.dao.base.product.ProductDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.buy.order.OrderDAO;
import zy.dao.buy.supply.SupplyDAO;
import zy.dao.stock.useable.UseableDAO;
import zy.dao.sys.print.PrintDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.base.product.T_Base_Barcode;
import zy.entity.base.product.T_Base_Product;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.buy.order.T_Buy_Import;
import zy.entity.buy.order.T_Buy_Order;
import zy.entity.buy.order.T_Buy_OrderList;
import zy.entity.buy.order.T_Buy_Product;
import zy.entity.sys.set.T_Sys_Set;
import zy.entity.sys.user.T_Sys_User;
import zy.service.buy.order.OrderService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.buy.BuyVO;
import zy.vo.common.SizeHorizontalVO;

@Service
public class OrderServiceImpl implements OrderService{
	@Resource
	private OrderDAO orderDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	
	@Resource
	private PrintDAO printDAO;
	
	@Resource
	private SupplyDAO supplyDAO;
	
	@Resource
	private UseableDAO useableDAO;
	
	@Resource
	private ProductDAO productDAO;
	
	@Resource
	private DepotDAO depotDAO;

	@Override
	public PageData<T_Buy_Order> page(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if(CommonUtil.THREE.equals(params.get(CommonUtil.SHOP_TYPE))){//自营店
			params.put("depot_codes", depotDAO.listDepotByShop(params.get(CommonUtil.SHOP_CODE).toString(), companyid));
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = orderDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Buy_Order> list = orderDAO.list(params);
		PageData<T_Buy_Order> pageData = new PageData<T_Buy_Order>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public PageData<T_Buy_Order> page4Enter(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		if(CommonUtil.THREE.equals(params.get(CommonUtil.SHOP_TYPE))){//自营店
			params.put("depot_codes", depotDAO.listDepotByShop(params.get(CommonUtil.SHOP_CODE).toString(), companyid));
		}
		
		Integer totalCount = orderDAO.count4Enter(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Buy_Order> list = orderDAO.list4Enter(params);
		PageData<T_Buy_Order> pageData = new PageData<T_Buy_Order>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@Override
	public T_Buy_Order load(Integer od_id) {
		T_Buy_Order order = orderDAO.load(od_id);
		if(order != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(order.getOd_number(), order.getCompanyid());
			if(approve_Record != null){
				order.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return order;
	}
	
	@Override
	public List<T_Buy_OrderList> detail_list(Map<String, Object> params) {
		return orderDAO.detail_list(params);
	}
	
	@Override
	public List<T_Buy_OrderList> detail_sum(Map<String, Object> params) {
		return orderDAO.detail_sum(params);
	}
	
	@Override
	public Map<String, Object> detail_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = orderDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}
	
	@Override
	public Map<String, Object> detail_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = orderDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "odl_pd_code,odl_pi_type,odl_cr_code,odl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Buy_OrderList> temps = orderDAO.detail_list(params);
		return BuyVO.getJsonSizeData_Order(sizeGroupList, temps);
	}
	
	@Override
	public List<T_Buy_OrderList> temp_list(Map<String, Object> params) {
		return orderDAO.temp_list(params);
	}
	
	@Override
	public List<T_Buy_OrderList> temp_sum(Integer od_type, Integer us_id, Integer companyid) {
		return orderDAO.temp_sum(od_type, us_id, companyid);
	}
	
	@Override
	public Map<String, Object> temp_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = orderDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}

	@Override
	public Map<String, Object> temp_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = orderDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "odl_pd_code,odl_pi_type,odl_cr_code,odl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Buy_OrderList> temps = orderDAO.temp_list(params);
		return BuyVO.getJsonSizeData_Order(sizeGroupList, temps);
	}
	
	@Override
	@Transactional
	public Map<String, Object> temp_save_bybarcode(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer od_type = (Integer)params.get("od_type");
		String barcode = (String)params.get("barcode");
		Integer amount = (Integer)params.get("amount");
		Integer priceType = (Integer)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		T_Sys_User user = (T_Sys_User)params.get("user");
		T_Base_Barcode base_Barcode = productDAO.loadBarcode(barcode, user.getCompanyid());
		if(base_Barcode == null){
			resultMap.put("result", 3);//条码不存在
			return resultMap;
		}
		T_Buy_OrderList temp = orderDAO.temp_loadBySubCode(base_Barcode.getBc_subcode(), "0", od_type, user.getUs_id(), user.getCompanyid());
		if (temp != null) {//临时表存在则直接更新数量
			temp.setOdl_amount(temp.getOdl_amount()+amount);
			orderDAO.temp_update(temp);
			resultMap.put("result", 1);//update
			resultMap.put("temp", temp);
			return resultMap;
		}
		T_Base_Product base_Product = orderDAO.load_product(base_Barcode.getBc_pd_code(), user.getCompanyid());
		Double unitPrice = orderDAO.temp_queryUnitPrice(base_Barcode.getBc_pd_code(),"0", od_type, user.getUs_id(), user.getCompanyid());;
		if(unitPrice == null){
			if("1".equals(priceType)){//最后一次进价
				unitPrice = base_Product.getPd_buy_price();
			}else {//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		temp = new T_Buy_OrderList();
		temp.setOdl_pd_code(base_Barcode.getBc_pd_code());
		temp.setOdl_cr_code(base_Barcode.getBc_color());
		temp.setOdl_sz_code(base_Barcode.getBc_size());
		temp.setOdl_szg_code(base_Product.getPd_szg_code());
		temp.setOdl_br_code(base_Barcode.getBc_bra());
		temp.setOdl_sub_code(temp.getOdl_pd_code()+temp.getOdl_cr_code()+temp.getOdl_sz_code()+temp.getOdl_br_code());
		temp.setOdl_amount(amount);
		temp.setOdl_realamount(0);
		temp.setOdl_unitprice(unitPrice);
		temp.setOdl_retailprice(base_Product.getPd_sell_price());
		temp.setOdl_remark("");
		temp.setOdl_pi_type(0);//商品
		temp.setOdl_type(od_type);
		temp.setOdl_us_id(user.getUs_id());
		temp.setCompanyid(user.getCompanyid());
		orderDAO.temp_save(temp);
		temp.setPd_no(base_Product.getPd_no());
		temp.setPd_name(base_Product.getPd_name());
		temp.setPd_unit(base_Product.getPd_unit());
		temp.setBd_name(base_Product.getPd_bd_name());
		temp.setTp_name(base_Product.getPd_tp_name());
		temp.setCr_name(base_Barcode.getBc_colorname());
		temp.setSz_name(base_Barcode.getBc_sizename());
		temp.setBr_name(base_Barcode.getBc_braname());
		resultMap.put("result", 2);//add
		resultMap.put("temp", temp);
		return resultMap;
	}
	
	@Override
	@Transactional
	public void temp_save(Map<String, Object> params) {
		List<T_Buy_OrderList> temps = (List<T_Buy_OrderList>)params.get("temps");
		Integer od_type = (Integer)params.get("od_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object pd_code = params.get("pd_code");
		Object unitPrice = params.get("unitPrice");
		if (temps != null && temps.size() > 0) {
			List<T_Buy_OrderList> temps_add = new ArrayList<T_Buy_OrderList>();
			List<T_Buy_OrderList> temps_update = new ArrayList<T_Buy_OrderList>();
			List<T_Buy_OrderList> temps_del = new ArrayList<T_Buy_OrderList>();
			for (T_Buy_OrderList item : temps) {
				if ("add".equals(item.getOperate_type())){
					if (item.getOdl_amount() > 0) {
						temps_add.add(item);
					}
				}else if("update".equals(item.getOperate_type())){
					if(!item.getOdl_amount().equals(0)){
						temps_update.add(item);
					}else {
						temps_del.add(item);
					}
				}
			}
			if (temps_add.size() > 0) {
				orderDAO.temp_save(temps_add);
			}
			if (temps_update.size() > 0) {
				orderDAO.temp_update(temps_update);
			}
			if (temps_del.size() > 0) {
				orderDAO.temp_del(temps_del);
			}
		}
		if (StringUtil.isNotEmpty(pd_code) && StringUtil.isNotEmpty(unitPrice)) {
			orderDAO.temp_updateprice(pd_code.toString(),"0", Double.parseDouble(unitPrice.toString()), od_type, user.getUs_id(), user.getCompanyid());
		}
	}
	
	@Override
	@Transactional
	public void temp_import(Map<String, Object> params) {
		List<String[]> datas = (List<String[]>)params.get("datas");
		Integer od_type = (Integer)params.get("od_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object priceType = params.get("priceType");
		Object sp_rate = params.get("sp_rate");
		List<String> barcodes = new ArrayList<String>();
		Map<String, Integer> data_amount = new HashMap<String, Integer>();
		for (String[] data : datas) {
			barcodes.add(data[0]);
			data_amount.put(data[0], Integer.parseInt(data[1]));
		}
		List<T_Buy_Import> imports = orderDAO.temp_listByImport(barcodes, user.getCompanyid());
		if (imports == null || imports.size() == 0) {
			throw new RuntimeException("无数据可导入");
		}
		Map<String, Double> unitPriceMap = new HashMap<String, Double>();
		Map<String, T_Buy_OrderList> tempsMap = new HashMap<String, T_Buy_OrderList>();
		List<T_Buy_OrderList> temps = orderDAO.temp_list_forimport(od_type, user.getUs_id(), user.getCompanyid());
		for (T_Buy_OrderList temp : temps) {
			if(!unitPriceMap.containsKey(temp.getOdl_pd_code())){
				unitPriceMap.put(temp.getOdl_pd_code(), temp.getOdl_unitprice());
			}
			tempsMap.put(temp.getOdl_sub_code(), temp);
		}
		List<T_Buy_OrderList> temps_add = new ArrayList<T_Buy_OrderList>();
		List<T_Buy_OrderList> temps_update = new ArrayList<T_Buy_OrderList>();
		for (T_Buy_Import item : imports) {
			if(tempsMap.containsKey(item.getBc_subcode())){//临时表已存在，更新数量
				T_Buy_OrderList temp = tempsMap.get(item.getBc_subcode());
				temp.setOdl_amount(temp.getOdl_amount()+data_amount.get(item.getBc_barcode()));
				temps_update.add(temp);
			}else {//临时表不存在，新增数据
				T_Buy_OrderList temp = new T_Buy_OrderList();
				temp.setOdl_pd_code(item.getBc_pd_code());
				temp.setOdl_sub_code(item.getBc_subcode());
				temp.setOdl_sz_code(item.getBc_size());
				temp.setOdl_szg_code(item.getPd_szg_code());
				temp.setOdl_cr_code(item.getBc_color());
				temp.setOdl_br_code(item.getBc_bra());
				temp.setOdl_amount(data_amount.get(item.getBc_barcode()));
				temp.setOdl_realamount(0);
				if(unitPriceMap.containsKey(item.getBc_pd_code())){//临时表已存在此货号，则使用临时表价格
					temp.setOdl_unitprice(unitPriceMap.get(item.getBc_pd_code()));
				}else{
					if("1".equals(priceType)){//最后一次进价
						temp.setOdl_unitprice(item.getUnit_price());
					}else {//按照折扣率
						temp.setOdl_unitprice(item.getRetail_price()* Double.parseDouble(StringUtil.trimString(sp_rate)));
					}
				}
				temp.setOdl_retailprice(item.getRetail_price());
				temp.setOdl_remark("");
				temp.setOdl_pi_type(0);//商品
				temp.setOdl_us_id(user.getUs_id());
				temp.setOdl_type(od_type);
				temp.setCompanyid(user.getCompanyid());
				temps_add.add(temp);
			}
		}
		if (temps_add.size() > 0) {
			orderDAO.temp_save(temps_add);
		}
		if (temps_update.size() > 0) {
			orderDAO.temp_updateById(temps_update);
		}
	}
	
	@Override
	@Transactional
	public void temp_import_draft(Map<String, Object> params) {
		String od_number = (String)params.get("od_number");
		Integer od_type = (Integer)params.get("od_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		List<T_Buy_OrderList> details = orderDAO.detail_list_forsavetemp(od_number,user.getCompanyid());
		if (details == null || details.size() == 0) {
			throw new RuntimeException("草稿不存在");
		}
		for(T_Buy_OrderList item:details){
			item.setOdl_us_id(user.getUs_id());
		}
		orderDAO.temp_clear(od_type, user.getUs_id(), user.getCompanyid());
		orderDAO.temp_save(details);
		orderDAO.del(od_number, user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_updateAmount(T_Buy_OrderList temp) {
		orderDAO.temp_update(temp);
	}
	
	@Override
	@Transactional
	public void temp_updatePrice(T_Buy_OrderList temp) {
		orderDAO.temp_updateprice(temp.getOdl_pd_code(), StringUtil.trimString(temp.getOdl_pi_type()),
				temp.getOdl_unitprice(), temp.getOdl_type(),
				temp.getOdl_us_id(), temp.getCompanyid());
		
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkById(T_Buy_OrderList temp) {
		orderDAO.temp_updateRemarkById(temp);
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkByPdCode(T_Buy_OrderList temp) {
		orderDAO.temp_updateRemarkByPdCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_del(Integer odl_id) {
		orderDAO.temp_del(odl_id);
	}

	@Override
	@Transactional
	public void temp_delByPiCode(T_Buy_OrderList temp) {
		if (temp.getCompanyid() == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if (temp.getOdl_us_id() == null) {
			throw new IllegalArgumentException("参数us_id不能为null");
		}
		if (temp.getOdl_type() == null) {
			throw new IllegalArgumentException("参数odl_type不能为null");
		}
		orderDAO.temp_delByPiCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_clear(Integer od_type,Integer us_id,Integer companyid) {
		orderDAO.temp_clear(od_type, us_id, companyid);;
	}
	
	@Override
	public PageData<T_Base_Product> page_product(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = orderDAO.count_product(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Product> list = orderDAO.list_product(param);
		PageData<T_Base_Product> pageData = new PageData<T_Base_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> temp_loadproduct(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sys_Set sysSet = (T_Sys_Set)params.get(CommonUtil.KEY_SYSSET);
		Integer us_id = (Integer)params.get("us_id");
		String pd_code = (String)params.get("pd_code");
		String dp_code = (String)params.get("dp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		Integer od_type = (Integer)params.get("od_type");
		String exist = (String)params.get("exist");
		String odl_pi_type = (String)params.get("odl_pi_type");
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		T_Base_Product base_Product = orderDAO.load_product(pd_code, companyid);
		Map<String, Object> product = new HashMap<String, Object>();
		product.put("pd_id", base_Product.getPd_id());
		product.put("pd_code", base_Product.getPd_code());
		product.put("pd_no", base_Product.getPd_no());
		product.put("pd_name", base_Product.getPd_name());
		product.put("pd_szg_code", base_Product.getPd_szg_code());
		product.put("pd_unit", base_Product.getPd_unit());
		product.put("pd_year", base_Product.getPd_year());
		product.put("pd_season", base_Product.getPd_season());
		product.put("pd_sell_price", base_Product.getPd_sell_price());
		product.put("pdm_buy_price", base_Product.getPd_buy_price());
		product.put("pd_bd_name", base_Product.getPd_bd_name());
		product.put("pd_tp_name", base_Product.getPd_tp_name());
		product.put("pdm_img_path", StringUtil.trimString(base_Product.getPdm_img_path()));
		Double unitPrice = null;
		if("1".equals(exist)){//已经录入从临时表中查询单价
			unitPrice = orderDAO.temp_queryUnitPrice(pd_code,odl_pi_type, od_type, us_id, companyid);
			product.put("temp_unitPrice", StringUtil.trimString(unitPrice));
		}
		if(unitPrice == null){
			if("1".equals(priceType)){//最后一次进价
				unitPrice = base_Product.getPd_buy_price();
			}else {//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		product.put("unitPrice", unitPrice);
		resultMap.put("product", product);
		params.put("szg_code", base_Product.getPd_szg_code());
		Map<String, Object> productMap = orderDAO.load_product_size(params);
		List<T_Base_Size> sizes=(List<T_Base_Size>)productMap.get("sizes");
		List<T_Buy_Product> inputs=(List<T_Buy_Product>)productMap.get("inputs");
		List<T_Buy_Product> temps=(List<T_Buy_Product>)productMap.get("temps");
		List<T_Buy_Product> stocks=(List<T_Buy_Product>)productMap.get("stocks");
		Map<String,Object> usableStockMap = null;
		if (sysSet.getSt_useable() != null && sysSet.getSt_useable().intValue() == 1) {
			usableStockMap = useableDAO.loadUseableStock(pd_code, dp_code, companyid);
		}
		resultMap.putAll(BuyVO.buildJsonProductInput(pd_code, sizes, inputs, stocks, temps, usableStockMap));
		return resultMap;
	}

	@Override
	@Transactional
	public void save(T_Buy_Order order, T_Sys_User user) {
		if(order == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(order.getOd_supply_code())){
			throw new IllegalArgumentException("供应商不能为空");
		}
		if(StringUtil.isEmpty(order.getOd_depot_code())){
			throw new IllegalArgumentException("仓库不能为空");
		}
		if(StringUtil.isEmpty(order.getOd_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		order.setCompanyid(user.getCompanyid());
		order.setOd_us_id(user.getUs_id());
		order.setOd_maker(user.getUs_name());
		order.setOd_state(0);
		order.setOd_realamount(0);
		order.setOd_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		order.setOd_sysdate(DateUtil.getCurrentTime());
		//1.查临时表
		List<T_Buy_OrderList> temps = orderDAO.temp_list_forsave(order.getOd_type(), user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("订单已保存，请勿重复提交");
		}
		//2.保存主表
		int od_amount = 0;
		double od_money = 0d;
		for (T_Buy_OrderList temp : temps) {
			od_amount += temp.getOdl_amount();
			od_money += temp.getOdl_amount() * temp.getOdl_unitprice();
		}
		order.setOd_amount(od_amount);
		order.setOd_money(od_money);
		orderDAO.save(order);
		//2.保存明细子表
		for (T_Buy_OrderList temp : temps) {
			temp.setOdl_number(order.getOd_number());
		}
		orderDAO.saveList(temps);
		//3.删除临时表
		orderDAO.temp_clear(order.getOd_type(), user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void update(T_Buy_Order order, T_Sys_User user) {
		if(order == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(order.getOd_supply_code())){
			throw new IllegalArgumentException("供应商不能为空");
		}
		if(StringUtil.isEmpty(order.getOd_depot_code())){
			throw new IllegalArgumentException("仓库不能为空");
		}
		if(StringUtil.isEmpty(order.getOd_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		order.setCompanyid(user.getCompanyid());
		order.setOd_us_id(user.getUs_id());
		order.setOd_maker(user.getUs_name());
		order.setOd_state(0);
		order.setOd_realamount(0);
		order.setOd_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		//1.1查临时表
		List<T_Buy_OrderList> temps = orderDAO.temp_list_forsave(order.getOd_type(), user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("订单已修改，请勿重复提交");
		}
		//1.2验证单据
		T_Buy_Order oldOrder = orderDAO.check(order.getOd_number(), user.getCompanyid());
		if (oldOrder == null || !CommonUtil.AR_STATE_FAIL.equals(oldOrder.getOd_ar_state())) {
			throw new RuntimeException("订单已修改，请勿重复提交");
		}
		//1.3删除子表
		orderDAO.deleteList(order.getOd_number(), user.getCompanyid());
		
		//2.保存主表
		int od_amount = 0;
		double od_money = 0d;
		for (T_Buy_OrderList temp : temps) {
			od_amount += temp.getOdl_amount();
			od_money += temp.getOdl_amount() * temp.getOdl_unitprice();
		}
		order.setOd_amount(od_amount);
		order.setOd_money(od_money);
		orderDAO.update(order);
		//2.保存明细子表
		for (T_Buy_OrderList temp : temps) {
			temp.setOdl_number(order.getOd_number());
		}
		orderDAO.saveList(temps);
		//3.删除临时表
		orderDAO.temp_clear(order.getOd_type(), user.getUs_id(), user.getCompanyid());
	}

	@Override
	@Transactional
	public T_Buy_Order approve(String number, T_Approve_Record record, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Order order = orderDAO.check(number, user.getCompanyid());
		if(order == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(order.getOd_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		//更新单据审核状态
		order.setOd_ar_state(record.getAr_state());
		order.setOd_ar_date(DateUtil.getCurrentTime());
		order.setOd_ar_name(user.getUs_name());
		orderDAO.updateApprove(order);
		//保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_buy_order");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		return order;
	}
	
	@Override
	@Transactional
	public T_Buy_Order stop(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Order order = orderDAO.check(number, user.getCompanyid());
		if(order == null){
			throw new RuntimeException("单据不存在");
		}
		if(!(CommonUtil.AR_STATE_APPROVED.equals(order.getOd_ar_state()))){
			throw new RuntimeException("单据未审核通过");
		}
		if (!order.getOd_state().equals(0) && !order.getOd_state().equals(4)) {
			throw new RuntimeException("单据状态不能被终止");
		}
		order.setOd_state(2);
		orderDAO.updateStop(order);
		//保存审批表终止记录
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_STOP);
		record.setAr_describe("");
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_buy_order");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		return order;
	}

	@Override
	@Transactional
	public void initUpdate(String number,Integer od_type, Integer us_id, Integer companyid) {
		List<T_Buy_OrderList> details = orderDAO.detail_list_forsavetemp(number,companyid);
		for(T_Buy_OrderList item:details){
			item.setOdl_us_id(us_id);
		}
		orderDAO.temp_clear(od_type, us_id, companyid);
		orderDAO.temp_save(details);
	}
	
	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Order order = orderDAO.check(number, companyid);
		if(order == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(order.getOd_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(order.getOd_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		orderDAO.del(number, companyid);
	}

	@Override
	public Map<String, Object> loadPrintData(String number, Integer sp_id, Integer displayMode,T_Sys_User user) {
		Map<String, Object> resultMap = printDAO.loadPrint4Bill(sp_id);
		T_Buy_Order order = orderDAO.load(number,user.getCompanyid());
		List<T_Buy_OrderList> orderList = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("odl_number", number);
		params.put("companyid", user.getCompanyid());
		if(displayMode.intValue() == 2){//汇总模式
			orderList = orderDAO.detail_sum(params);
		}else {
			orderList = orderDAO.detail_list_print(params);
		}
		resultMap.put("order", order);
		resultMap.put("orderList", orderList);
		resultMap.put("supply", supplyDAO.load(order.getOd_supply_code(), user.getCompanyid()));
		if(displayMode.intValue() == 1){//尺码模式查询
			List<String> szgCodes = new ArrayList<String>();
			for (T_Buy_OrderList item : orderList) {
				if(!szgCodes.contains(item.getOdl_szg_code())){
					szgCodes.add(item.getOdl_szg_code());
				}
			}
			List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, user.getCompanyid());
			resultMap.put("sizeGroupList", sizeGroupList);
		}
		return resultMap;
	}

}
